package incontrol.core;

import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.transform;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.ConvertUtils;

import com.google.common.base.Function;

public class Config {

	private Map<String, Object> config;

	public Config(Map<String, Object> config) {
		this.config = config;
	}

	public String get(String key) {
		String val = replaceEnv(config.get(key));
		return val;
	}

	private String replaceEnv(Object o) {
		String val = (String) ConvertUtils.convert(o, String.class);
		if (val == null)
			return null;
		if (val.contains("${")) {
			StringBuffer sb = new StringBuffer();
			Pattern compile = Pattern.compile("\\$\\{(.*)}");
			Matcher m = compile.matcher(val);
			while (m.find()) {
				String key = m.group(1);
				String v = System.getenv(key);
				if (v != null) {
					m.appendReplacement(sb, v);
				}
			}
			m.appendTail(sb);
			return sb.toString();
		}
		return val;
	}

	public List<String> getList(String key) {
		List<Object> vals = newArrayList();
		if (config.get(key) instanceof List) {
			List<Object> all = (List<Object>) config.get(key);
			if (all != null) {
				vals.addAll(all);
			}
			return transform(vals, new Function<Object, String>() {
				public String apply(Object input) {
					return replaceEnv(input);
				}
			});
		} else {
			String val = get(key);
			if (val == null)
				return Collections.emptyList();
			return Collections.singletonList(val);
		}
	}
}
